#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''decompress ROS Node'''
#decompress string form aiui module 
#ungzip hex string
#output :json 
import rospy
import zlib
import binascii
import json
import sys
import base64
import types
import time

from pymongo import MongoClient
from manager.msg import *
from vlc.srv import Play
# import actionlib
reload(sys)
sys.setdefaultencoding('utf-8')

# http://blog.csdn.net/tsxw24/article/details/16121115
def json_get(json, l_key, default):  
    ret = json
    for k in l_key:
        if type(k) is types.IntType:
            if k < 0 : return default
            if not (type(ret) is types.ListType): return default
            if len(ret) <= k: return default
        elif type(k) is types.StringType:
            if not (type(ret) is types.DictType): return default
            if not ret.has_key(k): return default
        else:
            return default
        ret = ret[k]

    return ret

# uncompress_data = zlib.decompressobj(16+zlib.MAX_WBITS).decompress(binascii.a2b_hex('1F8B08000000000000001D8DB10EC2201445FFE5CE0C0FA556589D9DEA6E28795692FA68086A4CD37F97B29D9C9B9CBB2224292C056E85CF93862385288FB48B257D39C31D4F44DAD83351D7915118D9BFE0B4C2E53A8494B9B2E915C2D38BF0DC0A5EA6B97A6B37B5670F4DF2A71EDD7E4B1D4CF5A5117C7CC77B9BB0FD01EE79C88E8F000000'))
# print(binascii.b2a_hex(uncompress_data))
# print(uncompress_data.decode('utf-8)'))

from std_msgs.msg import String
from std_msgs.msg import Bool
from std_srvs.srv import Empty
from manager.srv import Switch
# from cob_mimic.srv import *
# from cob_mimic.msg import *

pub_guide = rospy.Publisher('guide', Pose, queue_size=10)
pub_unknow = rospy.Publisher('tts', String, queue_size=10)
pub_aiui_text = rospy.Publisher('listener', String, queue_size=10)
pub_aiui_result_text = rospy.Publisher('listener1', String, queue_size=10)

pub_wakeup = rospy.Publisher('wakeup', String, queue_size=10)
pub_sleep = rospy.Publisher('sleep', String, queue_size=10)
pub_get_info = rospy.Publisher('get_score', String, queue_size=10)
pub_handup = rospy.Publisher('handup', String, queue_size=10)
pub_handfree = rospy.Publisher('handfree', String, queue_size=10)
pub_ktv_guide = rospy.Publisher('ktv_guide', String, queue_size=10)
speak_info = rospy.Publisher('speak_info', String, queue_size=10)

# pub_ = rospy.Publisher('sleep', String, queue_size=10)
# client = actionlib.SimpleActionClient('mimic/set_mimic', cob_mimic.msg.SetMimicAction)
# rospy.wait_for_service('/play')
# play_service = rospy.ServiceProxy('play', Play)
infos = {
    "兔小贝": "文博会材料-梅县区概况、兔小贝简介、客家山歌",
    "奥迅":"梅县区概况",
    "洗手间":"厕所、浴室、盥洗�整理、梳洗功能， 洗手间俗称厕所，泛指由人类建造专供人类（或其他特指生物，如家畜）进行生�方，一般兼具整�分为男、女洗手间及伤残人士提供专用洗手间。"
}

mimics = [None, None, "sad", None, "wakeup", "sad", None, None, None, None, None, None, None,]

g_wake_up = False

def callback(data):
    uncompress_data = zlib.decompressobj(16 | zlib.MAX_WBITS).decompress(binascii.a2b_hex(data.data))

    result = json.loads(uncompress_data)

    eventType = json_get(result, ['content', 'eventType'], None)
    arg1 = json_get(result, ['content', 'arg1'], None)
    global g_wake_up
    if eventType == 4:#aiui wake up
        angle = json_get(result, ['content', 'info', 'angle'], 0)
        if angle == -1:
            g_wake_up = True
        # homeSwitch = rospy.ServiceProxy('gohomeswitch', Switch)
        # homeSwitch(False)
        # play_service("look.3gp")
        pub_aiui_text.publish("")
        pub_wakeup.publish("")
    if eventType == 3 and arg1 == 2:#aiui sleep
        g_wake_up = False
        # homeSwitch = rospy.ServiceProxy('gohomeswitch', Switch)
        # homeSwitch(True)
        # play_service("sad.3gp")
        pub_sleep.publish("")

    if not g_wake_up:
        return
    # print result
    aiui_text = json_get(result, ['content', 'result', 'intent', 'text'], None)
    nlp_text = json_get(result, ['content', 'info', 'result', 'text'], None)
    # print aiui_text.encode('utf-8')
    if aiui_text is not None:
        pub_aiui_text.publish(aiui_text.encode('utf-8'))
        answer_text = json_get(result, ['content', 'result', 'intent', 'answer','text'], "")
        pub_aiui_result_text.publish(answer_text.encode('utf-8'))
    if nlp_text is not None:
        pub_aiui_text.publish(nlp_text.encode('utf-8'))        
    # search name
    # rc = json_get(result, ['content', 'result', 'intent', 'rc'], None)
    # if rc == 4:
    #     pub_aiui_text.publish(json_get(result, ['content', 'result', 'intent', 'text'], None))
    #     return

    # demand_semantic = result['content']['result']['intent']['semantic'][0]
    demand_semantic = json_get(result, ['content', 'result', 'intent', 'semantic', 0], None)
    # print demand_semantic
    if demand_semantic:
        intent = json_get(demand_semantic, ['intent'], None)
        # if demand_semanic['intent'] == 'hospital_guide':
        print intent
        if intent == 'hospital_guide':
            slots = json_get(demand_semantic, ['slots', 0], None)
            print slots
            # slots = demand_semantic['slots'][0]
            db = MongoClient().eveapitest
            p = db.pose.find_one({
                # "name": slots['value']
                "name": json_get(slots, ['normValue'], '')
            }, {"name": 1,
                "x": 1,
                "y": 1,
                "yaw": 1})
            if p:
                pose = Pose()
                pose.name = p["name"]
                pose.x = p["x"]
                pose.y = p["y"]
                pose.yaw = p["yaw"]
                pub_guide.publish(pose)
                # pub_unknow.publish("好的,跟我走吧")
                # time.sleep(4)
                # pub_unknow.publish(infos[pose.name.encode('utf-8')])
            else:
                pub_unknow.publish("没有"+slots['value']+"这个地方")
        if intent == 'get_info':
            pub_get_info.publish("")
        if intent == 'handup':
            pub_handup.publish("")
        if intent == 'handfree':
            pub_handfree.publish("")
        if intent == 'ktv_guide':
            pub_ktv_guide.publish("")
        if intent == 'get_point':
            speak_info.publish(intent)
        if intent == 'get_balance':
            speak_info.publish(intent)
        if intent == 'get_consumption':
            speak_info.publish(intent)
        if intent == 'get_room':
            speak_info.publish(intent)

def ttsCallback(data):
    text = base64.b64decode(data.data)
    pub_aiui_result_text.publish(text)
    # if data.data == "start":
    #     play_service("talk.3gp")
    # else:
    #     play_service("look.3gp")
    # pass

def listener():
    rospy.init_node('decompress_hex', anonymous=True)
    rospy.Subscriber("aiuimsg", String, callback)
    rospy.Subscriber("tts_result", String, ttsCallback)
    rospy.spin()

if __name__ == '__main__':
    listener()


